package com.ashun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.ashun.dao.DictDataRepository;
import com.ashun.dao.DictTypeRepository;
import com.ashun.entity.DictData;
import com.ashun.entity.DictType;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xufeifei on 16/9/30.
 */
@Controller
public class HelloWorldContoller {

    @Autowired
    private DictTypeRepository dictTypeRepository;
    @Autowired
    private DictDataRepository dictDataRepository;

    @RequestMapping("/")
    public String  hello(HttpServletRequest httpServletRequest){
        System.out.println("第二个页面的开始"+httpServletRequest.getSession().getId());
         return "hello";
    }

    @RequestMapping("/dict")
    @ResponseBody
    public String DictTypePage(String cd,Pageable pageable,HttpServletRequest request){
        System.out.println("第二个页面的session"+request.getSession().getId());
//        Page<DictType> page = this.dictTypeRepository.findByDictTypeCd(cd,new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize()));
        Page<DictType> page = this.dictTypeRepository.findAll(new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize()));
        Map<String,Object> pager = new HashMap<String, Object>();
        pager.put("rows",page.getContent());
        pager.put("total",page.getTotalElements());
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(DictType.class);
        filter.getExcludes().addAll(Arrays.asList(new String[]{"dictDatas"}));
        JSON.DEFFAULT_DATE_FORMAT="yyyy-MM-dd HH:mm:ss";
        return JSON.toJSONString(pager,filter, SerializerFeature.WriteDateUseDateFormat);
    }

    @RequestMapping(value = "/saveDictType",method = RequestMethod.POST)
    @ResponseBody
    public void saveDictType(DictType dictType){
        dictType.setUpdatedDate(new Date());
        dictType.setCreatedDate(new Date());
        this.dictTypeRepository.save(dictType);
    }


    @RequestMapping(value = "/updateDictType",method = RequestMethod.POST)
    @ResponseBody
    public void updateDictType(DictType dictType){
        dictType.setUpdatedDate(new Date());
        this.dictTypeRepository.save(dictType);
    }
}
